#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Created on 06.11.2010
Copyright (C) 2010 Alexander S. Razzhivin ( site http://httpbots.com )

#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
# 
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
# 
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.
'''
import urllib2
import urllib
import re
import cookielib
import hashlib
import simplejson
import os

class PyVkApi:
    
    cookieFile = 'cookies.lwp'
    cj = None
    
    def __init__(self, email, password, uid, api_id):
        self.email = email
        self.password = password
        self.api_id = api_id
        self.v = '3.0'
        self.format = 'JSON'
        self.uid = uid
        self.set_sid_secret()
      
    def get_headers(self):
        return {'User-Agent' : 'Mozilla/5.0 (Windows; U; Windows NT 5.1; ru; rv:1.9.0.13) Gecko/2009073022 Firefox/3.0.13',
                   'Host' : 'vkontakte.ru',
                   'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8',
                   'Connection' : 'close',
                   'Pragma' : 'no-cache',
                   'Cache-Control' : 'no-cache'
                  }
      
    def __initCookies(self):
        '''Загружает куки и сохраняет их на диск в формате библиотеки libwww-perl'''
        self.cj = cookielib.LWPCookieJar()

        if self.cj is not None:
            if os.path.isfile(self.cookieFile):
                # if we have a cookie file already saved
                # then load the cookies into the Cookie Jar
                self.cj.load(self.cookieFile)

            # Now we need to get our Cookie Jar
            # installed in the opener;
            # for fetching URLs
            if cookielib is not None:
                # if we use cookielib
                # then we get the HTTPCookieProcessor
                # and install the opener in urllib2
                opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cj))
                urllib2.install_opener(opener)
                
    def get_s_value(self):
        # Возвращает уникальный идентификатор, который выдается на домене login.vk.com
        host = 'http://login.vk.com/?act=login'
        post = urllib.urlencode({'email' : self.email,
                                 'expire' : '',
                                 'pass' : self.password,
                                 'vk' : ''})

        headers = self.get_headers()
        headers.update({'Host' : 'login.vk.com', 'Referer' : 'http://vkontakte.ru/index.php'})

        data = self.request(host, post, headers)
        return re.findall(r"name='s' value='(.*?)'", data.read())[0]
   
    def login(self):
        host = 'http://vkontakte.ru/login.php?op=slogin'
        post = urllib.urlencode({'s' : self.get_s_value()})

        headers = self.get_headers()
        headers.update({'Referer' : 'http://login.vk.com/?act=login',
                        'Cookie' : 'remixchk=5; remixsid=nonenone'})
        
        if self.cj is None:
            self.__initCookies()
                          
        self.request(host, post, headers)
        self.cj.save(self.cookieFile)
        
    def set_sid_secret(self):

        self.login()
        
        host = 'http://vkontakte.ru/login.php?app='+self.api_id+'&layout=popup&type=browser'
 
        data = self.request(host, None, self.get_headers())
        url = data.geturl()
        self.sid    = re.findall(r"sid%22%3A%22(.+?)%22", url)[0]
        self.secret = re.findall(r"secret%22%3A%22(.+?)%22", url)[0]
    
    def request(self, host, post, headers):
        conn = urllib2.Request(host, post, headers)
        return urllib2.urlopen(conn) 
            
    def call(self, params):

        params.append('api_id='+self.api_id)
        params.append('format='+self.format)
        params.append('v='+self.v)

        sig = hashlib.md5(self.uid+''.join(self.__sort_params(params))+self.secret).hexdigest()
        
        params.append('sid='+self.sid)
        params.append('sig='+sig)
        
        url = 'http://api.vkontakte.ru/api.php?'+'&'.join(self.__sort_params(params))
        result = simplejson.load(urllib.urlopen(url))

        try:
          return result['response']
        except KeyError:
          return result['error']
    
    def __sort_params(self, params):
        params.sort()
        return params

      
def main():
  vkapi = PyVkApi(email='test@test.com', password='', uid='1587648', api_id='2006539')
  
  from pprint import pprint
  pprint(vkapi.call(['method=friends.get','fields=photo_big']))
  
if __name__ == '__main__':
  main()

